package com.christina.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 启动检查服务
 * 检查Redis和RabbitMQ连接状态
 * 
 * @author Christina
 */
@Slf4j
@Service
public class StartupCheckService implements ApplicationRunner {

    private final StringRedisTemplate stringRedisTemplate;
    private final RabbitTemplate rabbitTemplate;

    public StartupCheckService(StringRedisTemplate stringRedisTemplate, RabbitTemplate rabbitTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void run(ApplicationArguments args) {
        log.info("开始启动检查...");
        
        checkRedisConnection();
        checkRabbitMQConnection();
        
        log.info("启动检查完成");
    }

    /**
     * 检查Redis连接
     */
    private void checkRedisConnection() {
        try {
            String testKey = "startup:check:redis";
            String testValue = "connected";
            
            // 测试Redis连接
            stringRedisTemplate.opsForValue().set(testKey, testValue);
            String result = stringRedisTemplate.opsForValue().get(testKey);
            stringRedisTemplate.delete(testKey);
            
            if (testValue.equals(result)) {
                log.info("✅ Redis连接正常");
            } else {
                log.warn("⚠️ Redis连接异常，返回值不匹配");
            }
        } catch (Exception e) {
            log.error("❌ Redis连接失败: {}", e.getMessage());
        }
    }

    /**
     * 检查RabbitMQ连接
     */
    private void checkRabbitMQConnection() {
        try {
            // 测试RabbitMQ连接
            rabbitTemplate.getConnectionFactory().createConnection().close();
            log.info("✅ RabbitMQ连接正常");
        } catch (Exception e) {
            log.error("❌ RabbitMQ连接失败: {}", e.getMessage());
        }
    }
}